//----------------------------------------
//
// Copyright © ying32. All Rights Reserved.
//
// Licensed under Apache License 2.0
//
//----------------------------------------

package dllimports

import (
	"syscall"
)

func newDLL(name string) (*DLL, error) {
	h, err := syscall.LoadLibrary(name)
	if err != nil {
		return nil, err
	}

	return &DLL{
		name:   name,
		handle: Handle(h),
	}, nil
}

func (d *DLL) release(h Handle) error {
	return syscall.FreeLibrary(syscall.Handle(h))
}

func (d *DLL) findProc(h Handle, name string) (*ProcAddr, error) {
	addr, err := syscall.GetProcAddress(syscall.Handle(h), name)
	if err != nil {
		return nil, err
	}

	return &ProcAddr{
		dll:  d,
		name: name,
		addr: Handle(addr),
	}, nil
}

func (p *ProcAddr) call(h Handle, args ...uintptr) (r1, r2 uintptr, err error) {
	return syscall.SyscallN(uintptr(h), args...)
}
